﻿#include "targetsheet.h"
#include "qapplication.h"
#include "qscreen.h"

//构造函数初始化
TargetSheet::TargetSheet(int size,QWidget *parent) : QLabel(parent)
{
  //使用qRegisterMetaType对自定义类型 QList<QPointF> 进行注册，否则无法通过信号传递
  qRegisterMetaType<QList<QPointF>>("QList<QPointF>");

  holeSize = size;

  create(holeSize);

}

TargetSheet::~TargetSheet()
{
  bulletImage = QPixmap();
  lastBulletImage = QPixmap();
}

void TargetSheet::create(int size)
{

  //获取屏幕属性
  QScreen *screen = QApplication::primaryScreen();

  qreal lcd_width = screen->size().width();
  qreal lcd_height = screen->size().height();

  //靶纸外观初始化
  this->setGeometry(QRect(0, 0, 801, 801));
  this->setScaledContents(true);
  this->setFixedSize(this->width(), this->height());
  this->setStyleSheet("QLabel{width: 100px;height: 100px;border: 1px solid green;border-radius: 10px;background-color: white}");

  //加载背景
  backgroundImage.load(":/source/circle-print.gif");
  this->setPixmap(QPixmap::fromImage(backgroundImage));

  //弹孔列表初始化
  onlyHoleList = {};

  //加载弹孔图片，并求取弹孔中心坐标
  bulletImage = QPixmap(":/source/bulletHole.png").scaled(size,size);
  lastBulletImage = QPixmap(":/source/blue.png").scaled(size,size);
  bulletCenter = QPointF(bulletImage.size().width()/2.0, bulletImage.size().height()/2.0);

}

//重载父类绘制方法
void TargetSheet::paintEvent(QPaintEvent *event)
{
  //    this->clear();
  //调用父类方法进行窗体绘制
  this->QLabel::paintEvent(event);

  //进行弹孔中心坐标校准，并画出弹孔
  QPainter painter(this);
  int i = 1;
  QPointF pointF;
  foreach(pointF, onlyHoleList)
    {
      painter.setPen(QPen(Qt::red,10));
      painter.setFont(QFont("宋体",10,10));
      painter.drawPixmap(pointF - bulletCenter + QPointF(curX,curY), bulletImage);
      painter.drawText(pointF - bulletCenter + QPointF(4,-8) + QPointF(curX,curY),QString::asprintf("%d",i));
      if(i == onlyHoleList.length())
        {
          pointF = onlyHoleList[onlyHoleList.length() - 1];
          painter.drawPixmap(pointF - bulletCenter + QPointF(curX,curY), lastBulletImage);
        }
      i = i + 1;
    }
}

void TargetSheet::updateHoles(const QList<QPointF>&  msg)
{
  onlyHoleList.clear();
  onlyHoleList = msg;
  update();
}

void TargetSheet::updateSize(double size)
{
  //加载弹孔图片，并求取弹孔中心坐标
  bulletImage = QPixmap(":/source/bulletHole.png").scaled(holeSize * size,holeSize * size);
  lastBulletImage = QPixmap(":/source/blue.png").scaled(holeSize * size,holeSize * size);
  bulletCenter = QPointF(bulletImage.size().width()/2.0 * size, bulletImage.size().height()/2.0 * size);
}

void TargetSheet::getX(int x)
{
  curX = x;
  update();
}

void TargetSheet::getY(int y)
{
  curY = y;
  update();
}
